
import styles from './index.less';
import { Space, Input, Button, message } from 'antd';
import ReactJson from 'react-json-view'
import React, { useState } from 'react';
import CodeRichText from '../../RichText/CodeRichText'
const { TextArea } = Input;



const JsonFormat = () => {

    const [data, setData] = useState({ src: {} });
    const [value, setValue] = useState();

    const onChange = (event) => {
        event.persist();  // 莫名其妙报错
        setValue(event.target.value);
        try {
            let src = eval(`(${event.target.value})`)
            setData({ src: src });
        } catch (err) {
            setData({ e: err });
        }
        
    };

   

    const onClickCompress = () => {
        try {
            let jsonStr = JSON.stringify(data.src);
            setValue(jsonStr);
        } catch (e) {
            message.error(e+"")
        }
    }

    const onClickFormat = () => {
        try {
            let jsonStr = JSON.stringify(data.src, null, "\t");
            setValue(jsonStr);
        } catch (e) {
            message.error(e+"")
        }
    }

    return (
        <div >
            <div style={{
                marginBottom:10
            }}>
                <Space>
                <Button size="small" onClick={onClickFormat}>格式化</Button>
                <Button size="small" onClick={onClickCompress}>压缩</Button>
                </Space>
            </div>
            <div className={styles.container}>
                <TextArea autoSize={false} 
                    placeholder="双击格式化"
                    onChange={onChange} 
                    onDoubleClick={onClickFormat}
                    value={value}></TextArea>
                <div className={styles.splite}></div>
                <div className={styles.reactJson}>
                    {data.src ? (<ReactJson src={data.src}
                        displayDataTypes={false}
                        name={false}
                        collapseStringsAfterLength={50}
                    ></ReactJson>) : (<div>{data.e + ""}</div>)}
                </div>
            </div>

        </div>
    )
}

export default JsonFormat;